package com.whq.knowverywell.activity;

import java.text.DecimalFormat;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.SparseArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
import com.whq.knowverywell.R;
import com.whq.knowverywell.activity.BaseLoginActivity.OnSortListener;
import com.whq.knowverywell.activity.ContentFragment.OnSumDataListener;
import com.whq.knowverywell.adapter.ContentFragmentAdapter;
import com.whq.knowverywell.business.LoginUtil;
import com.whq.knowverywell.util.DisplayUtil;
import com.whq.knowverywell.util.LogUtil;
import com.whq.knowverywell.util.StringUtil;
import com.whq.knowverywell.util.constant.ModelConstant;
import com.whq.knowverywell.util.constant.ParamConstant;
import com.whq.knowverywell.view.PageIndicator;
import com.whq.knowverywell.view.TitlePageIndicator;

/**
 * content frame
 * 
 * @author daiwei
 *
 */
public class ContentFrameActivity extends BaseLoginActivity implements ActionBar.OnNavigationListener, OnSumDataListener, OnSortListener{
	private static final String TAG = ContentFrameActivity.class.getSimpleName();
	
	private ViewPager mViewPager;
	private PageIndicator mPageIndicator;
	private ContentFragmentAdapter mFragmentAdapter;
	private LinearLayout mBottomBarLinearLayout;
	
	private boolean isFirst = true;
	private int currentDurationType;
	private SparseArray<String> durationTypeArray = new SparseArray<String>(4);
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		LogUtil.d(TAG, "onCreate start ...");
		setTheme(R.style.Theme_Sherlock_Light);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.content_frame);
		
		mHiddenSortImageView = (ImageView) findViewById(R.id.sort_imageview);
		mHiddenRefreshImageView = (ImageView) findViewById(R.id.refresh_imageview);
		mHiddenManagerImageView = (ImageView) findViewById(R.id.manager_imageview);
		
		// init bottom bar 
        mSumTextView = (TextView) findViewById(R.id.sum_textview);
        mAmountTextView = (TextView) findViewById(R.id.amount_textview);
        mBottomBarLinearLayout = (LinearLayout) findViewById(R.id.bottom_linearlayout);
        mBottomBarLinearLayout.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                scrollListViewOfFragment2Top();
            }
        });
		
		// init content fragment 
		mFragmentAdapter = new ContentFragmentAdapter(getSupportFragmentManager());
		mFragmentAdapter.setBusinessType(itemId);
		mFragmentAdapter.setFragmentType(fragmentType);
		// 热销查询去掉当年
		if (itemId == ModelConstant.BUSINESS_TYPE_HOTSELL) {
		    mFragmentAdapter.setCount(3);
		}
		
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setAdapter(mFragmentAdapter);
		mPageIndicator = (TitlePageIndicator) findViewById(R.id.indicator);
		mPageIndicator.setViewPager(mViewPager);
		mPageIndicator.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int position) {
			    //TipUtil.tipDescription(ContentFrameActivity.this, "position[" + position + "]");
				
				if (!LoginUtil.chkLogin(ContentFrameActivity.this)) {
		            Toast.makeText(ContentFrameActivity.this, "您已经退出登录或者在其他设备上登录！", Toast.LENGTH_SHORT).show();

		            Intent intent = new Intent(ContentFrameActivity.this, LoginActivity.class);
		            startActivity(intent);
		            ContentFrameActivity.this.finish();
		            return;
		        }
				
			    switch (position) {
                case 0:
                    currentDurationType = ModelConstant.DURATION_TYPE_YESTERDAY;
                    break;
                case 1:
                    currentDurationType = ModelConstant.DURATION_TYPE_TODAY;
                    break;
                case 2:
                    currentDurationType = ModelConstant.DURATION_TYPE_MONTH;
                    break;
                case 3:
                    currentDurationType = ModelConstant.DURATION_TYPE_YEAR;
                    break;

                default:
                    currentDurationType = ModelConstant.DURATION_TYPE_TODAY;
                    break;
                }
			    
			    String data = durationTypeArray.get(currentDurationType);
			    if (!StringUtil.isEmpty(data)) {
			        String[] datas = data.split(":");
			        if (datas != null && datas.length > 1) {
			            mSumTextView.setText(datas[0]);
			            
			            // 格式化要显示的数字
			            double totalAmount = 0;
			            try {
			            	totalAmount = Double.parseDouble(datas[1]);
			            } catch (Exception e) {
			            	LogUtil.e(TAG, "[" + datas[1] + "] 转换成double出错", e);
			            }
			            
		                mAmountTextView.setText("￥" + new DecimalFormat(",###").format(totalAmount));
			        }
			    } else {
			        mSumTextView.setText("0");
                    mAmountTextView.setText("￥0.0");
			    }
			    
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				
			}
		});
		// set default page today
		durationType = ModelConstant.DURATION_TYPE_TODAY;
		mPageIndicator.setCurrentItem(1);
		
    	Context context = getSupportActionBar().getThemedContext();
    	if (!StringUtil.isEmpty(fragmentTitle) && fragmentType == ModelConstant.FRAGEMENT_TYPE_DETAIL) {
    		getSupportActionBar().setDisplayShowTitleEnabled(true);
    		getSupportActionBar().setTitle(fragmentTitle);
    	} else {
    		ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(context, R.array.homeitems, R.layout.self_sherlock_spinner_item);
    		list.setDropDownViewResource(R.layout.self_sherlock_spinner_dropdown_item);
    		getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
    		getSupportActionBar().setListNavigationCallbacks(list, (OnNavigationListener) this);
    		getSupportActionBar().setDisplayShowTitleEnabled(false);
    	}
		
    	mListener = this;
    	initSortPopupWindow();
	}
	
	@Override
	protected void getParameters() {
		super.getParameters();
		Intent intent = getIntent();
		if (intent != null) {
			itemId = intent.getIntExtra(ParamConstant.BUNDLE_KEY_ITEM_ID, -1);
			LogUtil.i(TAG, "parameter item id is : " + itemId);
			fragmentType = intent.getIntExtra(ParamConstant.BUNDLE_KEY_FRAGMENT_TYPE, ModelConstant.FRAGEMENT_TYPE_CONTENT);
			LogUtil.i(TAG, "parameter fragmentType is : " + fragmentType);
			productNo = intent.getStringExtra(ParamConstant.BUNDLE_KEY_PRODUCT_NO);
			LogUtil.i(TAG, "parameter productNo is : " + productNo);
			fragmentTitle = intent.getStringExtra(ParamConstant.BUNDLE_KEY_FRAGMENT_TITLE);
			LogUtil.i(TAG, "parameter fragmentTitle is : " + fragmentTitle);
		}
	}
	
	@Override
	protected void onResume() {
		LogUtil.d(TAG, "onResume start ...");
		super.onResume();
		
		if (fragmentType == ModelConstant.FRAGEMENT_TYPE_CONTENT) {
			getSupportActionBar().setSelectedNavigationItem(this.itemId - 1);
		} 
		
	}
	
	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		//Toast.makeText(this, "Selected: " + itemTitles[itemPosition], Toast.LENGTH_SHORT).show();
		if (fragmentType == ModelConstant.FRAGEMENT_TYPE_DETAIL) {
			return true;
		}
		
		if (!isFirst) {
			Intent intent = new Intent();
			if ((itemPosition+1) == ModelConstant.BUSINESS_TYPE_GOODS) {
				intent.setClass(this, ProductSearchActivity.class);
			} else {
				intent.setClass(this, ContentFrameActivity.class);
			}
		    intent.putExtra(ParamConstant.BUNDLE_KEY_ITEM_ID, itemPosition + 1);
		    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		    startActivity(intent);
		    this.finish();
		} else {
			isFirst = false;
		}
		
		return true;
	}

	@Override
	public void onSumData(int durationType, long totalSalesVolume, double totalSalesAmount) {
	    LogUtil.d(TAG, "onSumData durationType[" + durationType + "] totalSalesVolume[" + totalSalesVolume + "] totalSalesAmount[" + totalSalesAmount + "]");
	    durationTypeArray.put(durationType, totalSalesVolume + ":" + totalSalesAmount);
	    if (durationType == currentDurationType) {
	      mSumTextView.setText(totalSalesVolume + "");
	      mAmountTextView.setText("￥" + new DecimalFormat(",###").format(totalSalesAmount) );
	    }
	}

	@Override
	public String getProductNo() {
		return productNo;
	}

    @Override
    public void showSortPopupWindow(View anchor) {
        if (mSortPopupWindow != null && !mSortPopupWindow.isShowing()) {
            mSortPopupWindow.showAsDropDown(mHiddenSortImageView, 0, DisplayUtil.px2dip(-60, mDisplayMetrics.density));
        }
    }

    @Override
    public void showManagerPopupWindow(View anchor) {
        if (mManagerPopupWindow != null && !mManagerPopupWindow.isShowing()) {
            mManagerPopupWindow.showAsDropDown(mHiddenManagerImageView, 0, DisplayUtil.px2dip(-60, mDisplayMetrics.density));
        }
        
    }

	@Override
	public void doSortInPopupWindow(String orderBy) {
		LogUtil.d(TAG, "doSortInPopupWindow start ...");
        
		if (mSortPopupWindow != null && mSortPopupWindow.isShowing()) {
			mSortPopupWindow.dismiss();
		}
		
        ContentFragment fragment = mFragmentAdapter.getItem(currentDurationType-1);
        fragment.doSort(orderBy);
	}
    
	
	private void scrollListViewOfFragment2Top() {
	    LogUtil.d(TAG, "scrollListViewOfFragment2Top start ...");
        
        ContentFragment fragment = mFragmentAdapter.getItem(currentDurationType-1);
        fragment.scrollListViewOfFragment2Top();
	}
}
